package com.ccn.crm.interfaces.impl;

import com.ccn.crm.mapper.BeforeWorkingMapper;
import com.ccn.crm.mapper.EffortMapper;
import com.ccn.crm.mapper.MiddleTableMapper;
import com.ccn.crm.model.*;
import com.ccn.crm.service.*;
import com.ccn.crm.taskController.taskController;
import com.ccn.crm.util.BigDecimalUtil;
import com.ccn.crm.util.DateUtil;
import com.ccn.crm.util.EmailUtil;
import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import javax.mail.internet.InternetAddress;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Service
public class MailService implements IMail {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private EmailUtil emailUtil;
    @Autowired
    private EffortMapper effortMapper;
    @Autowired
    private IUserGroup iUserGroup;
    @Autowired
    private IUser iUser;
    @Autowired
    private IAfterSales iAfterSales;
    @Autowired
    private IAction iAction;
    @Autowired
    private IProduct iProduct;
    @Autowired
    private MiddleTableMapper middleTableMapper;
    @Autowired
    private IUnclaimedProject iUnclaimedProject;
    @Autowired
    private BeforeWorkingMapper beforeWorkingMapper;
    private static final Logger LOG = LoggerFactory.getLogger(MailService.class);
    @Override
    public void emailSend() {

        MailBean mailBean = new MailBean();
        mailBean.setSubject("每日填写工时提醒");
//        mailBean.setReceiptPeople("xiangyang.wang@yesno.com.cn");
        Date dates = new Date();
        List<WorkTime> workTimes=new ArrayList<>();
        AfterSales aLong=null;
        BeforeWorking beforeWorking=null;
        int dayFor = DateUtil.dayForWeek();
        String day="本";
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
        if (dayFor==1){

             workTimes = effortMapper.weekLastWorkDate();

            format = new SimpleDateFormat("yyyy-MM-dd ");
             day="上";
        }else {
             workTimes = effortMapper.weekWorkDate(dates);
        }

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式

        int sendSize = workTimes.size();
        //设置群发收件人
        String[] sent=new String[sendSize];
        String listDate= "";
        for (int j=0;j<sendSize;j++){

            WorkTime workTime = workTimes.get(j);
            //获取数据
            String name = workTime.getName();
            String dept = workTime.getDept();
            String position = workTime.getPosition();
            double dayWork=0.00;
            //获取当前是星期几
            int dayForWeek = DateUtil.dayForWeek();
            if (dayForWeek==1){
                //售前
                aLong = iAfterSales.selectLastWeekConsumedByName(name);
                //项目工时
                dayWork = effortMapper.selectDayWorkConsumeLast(name);
                //售前
                 beforeWorking = beforeWorkingMapper.selectLastWeekConsumedByName(name);
                dayForWeek=6;
            }else {
                aLong = iAfterSales.selectConsumedByName(name);
                dayWork = effortMapper.selectDayWorkConsume(name);
                beforeWorking = beforeWorkingMapper.selectConsumedByName(name);
            }
            Double workinghours=0.0d;
            Double workinghourSq=0.0d;
            if (aLong!=null){
                workinghours = aLong.getWorkinghours();
            }
            if (beforeWorking!=null){
                workinghourSq=Double.valueOf(beforeWorking.getWorkinghours());
            }

            Double consumed = workTime.getConsumed();
            String startTime = df.format(workTime.getStartTime());
            String endTime = format.format(workTime.getEndTime());
            String email = workTime.getEmail();
            if (email.equals("")) {
                sent[j]="hooverhuang@yesno.com.cn";
            }else {
                sent[j]=email;
            }

            double sum=consumed+workinghours+workinghourSq;
            String s1 = BigDecimalUtil.m2(consumed-dayWork);
            String s2 = BigDecimalUtil.m2(workinghours);
            String s3 = BigDecimalUtil.m2(dayWork);
            String s4 = BigDecimalUtil.m2(workinghourSq);
            //保留两位小数
            String su = BigDecimalUtil.m2(sum);
            double newWorkTime=(dayForWeek-1)*8;
            //算出平均工时
            double avg= sum/newWorkTime;
            DecimalFormat decimalFormat = new DecimalFormat("0.00%");
            String r = decimalFormat.format(avg);
            String percent="";
            if (avg<0.8){
                percent="<td style='width: auto;border:1px solid black;collapse:collapse;color:red'>"+r+"</td>\n" ;
            }else {
                percent="<td style='width: auto;border:1px solid black;collapse:collapse'>"+r+"</td>\n" ;
            }
            String date="<tr>\n" +
                    "            <td style='width: auto;border:1px solid black;collapse:collapse'>"+ name+"</td>\n" +
                    "            <td style='width: auto;border:1px solid black;collapse:collapse' >"+dept+"</td>\n" +
                    "            <td style='width: auto;border:1px solid black;collapse:collapse'>"+position+"</td>\n" +
                    "            <td style='width: auto;border:1px solid black;collapse:collapse'>"+s1+"</td>\n" +
                    "            <td style='width: auto;border:1px solid black;collapse:collapse'>"+s2+"</td>\n" +
                    "            <td style='width: auto;border:1px solid black;collapse:collapse'>"+s4+"</td>\n" +
                    "            <td style='width: auto;border:1px solid black;collapse:collapse'>"+s3+"</td>\n" +
                    "            <td style='width: auto;border:1px solid black;collapse:collapse'>"+su+"</td>\n" +
                                                                                                    percent+
                    "            <td style='width: auto;border:1px solid black;collapse:collapse'>"+startTime+"</td>\n" +
                    "            <td style='width: auto;border:1px solid black;collapse:collapse'>"+endTime+"</td>\n" +
                    "          </tr>";
            listDate+=date;
        }

        String content = "<html>\n" +
                "<body>\n" +
                "<h3>上海中商网络股份有限公司（项目组）</h3>\n" +
                "<h5 style='color:red'>请大家每日及时填写工时(包括售后工时)，以下为"+day+"周工时明细</h5>\n" +
                "<table  style='width: auto; min-width: 80% ;border:2px solid black'>\n" +
                "  <thead '>\n" +
                "    <tr>\n" +
                "                        <th  style='width: auto;border:1px solid black;collapse:collapse'>名字</th>\n" +
                "                        <th  style='width: auto;border:1px solid black;collapse:collapse'>部门</th>\n" +
                "                        <th  style='width: auto;border:1px solid black;collapse:collapse'>职位</th>\n" +
                "                        <th  style='width: auto;border:1px solid black;collapse:collapse'>项目工时</th>\n" +
                "                        <th  style='width: auto;border:1px solid black;collapse:collapse'>售后工时</th>\n" +
                "                        <th  style='width: auto;border:1px solid black;collapse:collapse'>售前工时</th>\n" +
                "                        <th  style='width: auto;border:1px solid black;collapse:collapse'>日常工时</th>\n" +
                "                        <th  style='width: auto;border:1px solid black;collapse:collapse'>周总工时</th>\n" +
                "                        <th  style='width: auto;border:1px solid black;collapse:collapse'>填写率 </th>\n" +
                "                        <th  style='width: auto;border:1px solid black;collapse:collapse'>开始时间</th>\n" +
                "                        <th  style='width: auto;border:1px solid black;collapse:collapse'>截算时间</th>\n" +
                "                </tr>\n" +
                "  </thead>\n" +
                "  <tbody '>"+
                listDate+
                " </tbody>"+
                "<body>\n" +
                "</html>\n";
            mailBean.setText(content);


        //获取抄送人
        List<userGroup> userGroupsList = iUserGroup.projectManagement();
        int size = userGroupsList.size();
        String[] cc=new String[size];

        for (int i=0;i<size;i++){
            User user = iUser.selectByAccount(userGroupsList.get(i).getAccount());
            String email = user.getEmail();
            cc[i]=email;
        }
        System.out.println(sent);

        emailUtil.sendMailHtml(mailBean,sent,cc);
//        emailUtil.sendMailMe(mailBean.getText());
    }

    @Override
    public void projectAddRemind(MailBean mailBean) {

            mailBean.setSubject("新建项目提醒");
            String[] sentName = new String[1];
            sentName[0] = mailBean.getReceiptPeople();
            List<userGroup> userGroupsList = iUserGroup.projectManagement();
            int size = userGroupsList.size();
            String[] cc = new String[size];
            for (int i = 0; i < size; i++) {
                User user = iUser.selectByAccount(userGroupsList.get(i).getAccount());
                String email = user.getEmail();
                cc[i] = email;
            }
            String percent = "";
            if (mailBean.getProjectStatus().equals("7") && mailBean.getTransform().equals("N")) {
                mailBean.setSubject("新建项目提醒");
                percent = "新项目：" + mailBean.getProjectName() + " 在禅道创建成功，项目状态：待领取，项目经理：" + mailBean.getRealName();
            } else if (mailBean.getProjectStatus().equals("7") && mailBean.getTransform().equals("Y")) {
                mailBean.setSubject("项目启动提醒");
                percent = "项目：" + mailBean.getProjectName() + " 项目状态由：待分配--->待领取，项目经理：" + mailBean.getRealName();
            } else if (mailBean.getProjectStatus().equals("8")) {
                mailBean.setSubject("新建项目提醒");
                percent = "新项目：" + mailBean.getProjectName() + " 在禅道创建成功，项目状态：待分配（未下销售单，暂不启动），项目经理：" + mailBean.getRealName();
            } else if (mailBean.getProjectStatus().equals("XG")) {
                User manageNames = iUser.selectByName(mailBean.getTransform());
                if (null != manageNames) {
                    sentName[0] = manageNames.getEmail();
                }
                mailBean.setSubject("项目修改项目经理提醒");
                percent = "项目：" + mailBean.getProjectName() + " 项目经理由：" + mailBean.getTransform() + "修改为：" + mailBean.getRealName();
            }
            mailBean.setText(percent);
            emailUtil.sendMailHtml(mailBean, sentName, cc);
        }


    @Override
    public void projectStatusRemind() {
        Date date = new Date();
//        List<Action> actions = iAction.selectFirst();
        List<Product> products = iProduct.selectNotSentProduct();
        if (products.size()>1) {
            for (Product product:products) {
                Integer productId = product.getId();
                if (null==productId){
                    continue;
                }
                String stringId=","+productId+",";
                Action actionFirst = iAction.selectByProduct(stringId);
                if (actionFirst==null){
//                    System.out.println("s搜不到id："+stringId);
                }

                if (null != actionFirst) {
                    Date createTime = DateUtil.fourteenHoursBefore(actionFirst.getDate());
                    if (actionFirst.getExtra().equals("1")) {

                        if (DateUtil.formatDateTime(createTime)){
                            this.remindFirstEmail(product,"1","2","开发阶段","启动阶段和规划阶段");
                        }else if (DateUtil.differentDays(date,createTime)==7){
                            this.remindFirstEmail(product,"2","1","开发阶段","启动阶段和规划阶段");
                        }else if (DateUtil.differentDays(date,createTime)==14){
                            this.remindFirstEmail(product,"3",null,"开发阶段","启动阶段和规划阶段");
                        }
                    } else if (actionFirst.getExtra().equals("2")) {
                        //实施阶段发送项目开始阶段邮件
                        Action action = iAction.selectByProductAndStage(stringId, "1");

                        if (null!=action){
                            Date createDate = DateUtil.fourteenHoursBefore(action.getDate());

                            if (DateUtil.formatDateTime(createDate)){
                                this.remindFirstEmail(product,"1","2","开发阶段","启动阶段和规划阶段");
                            }else if (DateUtil.differentDays(date,createDate)==7){
                                this.remindFirstEmail(product,"2","1","开发阶段","启动阶段和规划阶段");
                            }else if (DateUtil.differentDays(date,createDate)==14){
                                this.remindFirstEmail(product,"3",null,"开发阶段","启动阶段和规划阶段");
                            }
                        }else {

                            if (DateUtil.formatDateTime(createTime)){
                                this.remindFirstEmail(product,"1","2","实施阶段","启动阶段和规划阶段");
                            }else if (DateUtil.differentDays(date,createTime)==7){
                                this.remindFirstEmail(product,"2","1","实施阶段","启动阶段和规划阶段");
                            }else if (DateUtil.differentDays(date,createTime)==14){
                                this.remindFirstEmail(product,"3",null,"实施阶段","启动阶段和规划阶段");
                            }
                        }

                    } else if (actionFirst.getExtra().equals("3")) {

                        if (DateUtil.formatDateTime(createTime)){
                            this.remindFirstEmail(product,"1","2","验收阶段","启动阶段，规划阶段和执行阶段");
                        }else if (DateUtil.differentDays(date,createTime)==7){
                            this.remindFirstEmail(product,"2","1","验收阶段","启动阶段，规划阶段和执行阶段");
                        }else if (DateUtil.differentDays(date,createTime)==14){
                            this.remindFirstEmail(product,"3",null,"验收阶段","启动阶段，规划阶段和执行阶段");
                        }
                    } else if (actionFirst.getExtra().equals("4")) {

                        if (DateUtil.formatDateTime(createTime)){
                            this.remindFirstEmail(product,"1","2","完成验收","启动阶段，规划阶段，执行阶段和收尾阶段");
                        }else if (DateUtil.differentDays(date,createTime)==7){
                            this.remindFirstEmail(product,"2","1","完成验收","启动阶段，规划阶段，执行阶段和收尾阶段");
                        }else if (DateUtil.differentDays(date,createTime)==14){
                            this.remindFirstEmail(product,"3",null,"完成验收","启动阶段，规划阶段，执行阶段和收尾阶段");
                        }

                    }
                }
            }
        }

    }

    @Override
    public void updateProductPo(MailBean mailBean) {

    }

    @Override
    public void sendSQEmail() {
        List<String> pid = iUnclaimedProject.selectNowUpdate();
        if (pid.size()>0){
            MailBean mailBean = new MailBean();
            mailBean.setSubject("【项目预警】售中人天成本预警");
            String text="";
            for (String id:pid) {

                Product productById = iProduct.getProductById(Integer.valueOf(id));
                if (productById!=null){
                    String name = productById.getName();
                    String po = productById.getPo();
                    double demandChange = productById.getDemandChange().floatValue();

                    double sqcost = productById.getSqcost().doubleValue();
                    double szcost = productById.getSzcost().doubleValue();
                    BigDecimal softwareamountoutsource = productById.getSoftwareamountoutsource();
                    double day = softwareamountoutsource.floatValue()/1200.0f;

                    if (sqcost<szcost+day||szcost==0||(szcost+day)<sqcost*0.8){
                        double much = day+szcost-sqcost;
                        //获取抄送人
                        User users = iUser.selectByAccount(po);
                        if (users!=null) {
                            mailBean.setReceiptPeople(users.getEmail());
                        }
                         text+="项目："+name+"<br> "+"项目经理："+users.getRealname()+"<br>"+"售前预估人天："+sqcost+"<br>"+"售中人天："+szcost+
                                "<br>"+"外包人天（外包金额/1200）："+day+"<br>"+"需求变更人天:"+demandChange+"<br>"+"超出人天："+much+"<br><br><br>";

                    }

                }
            }
            if (!text.equals("")) {
                mailBean.setText(text);
                List<userGroup> userGroupsList = iUserGroup.selectUserByGroup(33);
                int size = userGroupsList.size();
                String[] cc = new String[size];

                for (int i = 0; i < size; i++) {
                    User user = iUser.selectByAccount(userGroupsList.get(i).getAccount());
                    String email = user.getEmail();
                    cc[i] = email;
                }
                emailUtil.sendMailHtml(mailBean, cc);
            }
        }

    }

    private void remindFirstEmail(Product product,String number,String time ,String productStatus,String fileName){
        MailBean mailBean = new MailBean();

        List<userGroup> checkUsers = iUserGroup.selectUserByGroup(1);
        int size = checkUsers.size();
        String[] cc=new String[size];
        String[] sentName=new String[size];
        for (int i=0;i<size;i++){
            User checkUser = iUser.selectByAccount(checkUsers.get(i).getAccount());
            String email = checkUser.getEmail();
            cc[i]=email;
        }
        String name = product.getPo();
        User user = iUser.selectByAccount(name);
        if (null==user){
             sentName=new String[size];
            sentName=cc;
        }else {
            sentName=new String[1];
            sentName[0]=user.getEmail();
        }
//        String projectstatus = product.getProjectstatus();
        mailBean.setSubject("内审资料整理");
//        mailBean.setReceiptPeople(user.getEmail());
        //项目经理
        if (number.equals("1")) {
            String context="项目："+product.getName()+"-"+"项目状态："+productStatus+"-内审员将在"+time+"周后开始内审请准备"+fileName+"资料。";
            mailBean.setText(context);
          emailUtil.sendMailManyPro(mailBean,sentName);
        }
        if (number.equals("2")) {
            String context="项目："+product.getName()+"-"+"项目状态："+productStatus+"-内审员将在"+time+"周后开始内审请准备"+fileName+"资料。";
            mailBean.setText(context);
            emailUtil.sendMailManyPro(mailBean,sentName);
        }
        if (number.equals("3")) {

            String context="项目："+product.getName()+"-"+"项目状态："+productStatus+"-开始内审"+fileName+"资料。";
            mailBean.setText(context);
            emailUtil.sendMailHtml(mailBean,sentName,cc);
            if (product.getProjectstatus().equals("4")) {
                MiddleTable middleTable = new MiddleTable();
                middleTable.setProductid(product.getId());
                int insert = middleTableMapper.insert(middleTable);
                if (insert > 0) {
                    LOG.info("项目内审邮件发送成功,项目名称" + product.getName());
                }
            }
        }

    }

}
